package pers.xiqingbo.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @PackageName: pers.xiqingbo.web
 * @ClassName: BaseServlet
 * @Description: 公共的Servlet方法代码
 * @Author: Schieber
 * @Date: 2021/2/18 上午 7:21
 */
public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 子类继承父类非私有的方法，所以表单post提交后可以找到子类继承了父类的doPost方法执行
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String actionParameter = request.getParameter("action");
        try {
            // 获取action业务鉴别字符串，获取相应的业务方法反射对象
            Method declaredMethod = this.getClass().getDeclaredMethod(actionParameter, HttpServletRequest.class, HttpServletResponse.class);
            // 调用目标业务方法
            declaredMethod.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

/*        if ("register".equals(actionParameter)) {
            System.out.println("用户注册业务");
            register(request,response);
        } else if ("login".equals(actionParameter)) {
            System.out.println("用户登录业务");
            login(request,response);
        }*/
    }
}
